package com.vipbbo.security.distributed.uaa.service;

import com.alibaba.fastjson.JSON;
import com.vipbbo.security.distributed.uaa.dao.UserDao;
import com.vipbbo.security.distributed.uaa.model.UserDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author bbo(zbw)
 * Description 用户接口
 * @Date 2021/4/18
 */
@Service
public class SpringDataUserDetailsService implements UserDetailsService {

    @Autowired
    UserDao userDao;

    // 根据账号查询用户信息
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { //登录账号
        System.out.println("username=" + username); //根据账号去数据库查询...
        UserDto userDto = userDao.getUserByUsername(username);
        if (userDto == null) {
            return null;
        }
        // 根据用户的id 查询用户的权限
        List<String> permissions = userDao.findPermissionsByUserId(userDto.getId());
        //将permissions转成数组
        String[] permissionArray = new String[permissions.size()];
        permissions.toArray(permissionArray);
        // 将userDto转换成json
        String principal = JSON.toJSONString(userDto);
        //这里暂时使用静态数据
        UserDetails userDetails =
                //User.withUsername(userDto.getUsername()).password(userDto.getPassword()).authorities(permissionArray).build();
                User.withUsername(principal).password(userDto.getPassword()).authorities(permissionArray).build();
        return userDetails;
    }
}
